package com.hycc.base;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class FutureDemo {
    public static void main(String[] args) {
        //没有返回值的 CompletableFuture.runAsync() 异步回掉
        //发起一个请求
        Future<Void> future = CompletableFuture.runAsync(()->{
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("runAsync=>void");
        });
        System.out.println("1111");
        try {
            future.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        //有返回值的异步回调
        try {
            System.out.println(CompletableFuture.supplyAsync(() -> {
                //int i = 10 / 0;
                System.out.println("111");
                return "succes";
            }).whenComplete((t, u) -> {
                System.out.println("t=>" + t); //正常 正确执行的返回值 succes 错误 null
                System.out.println("u=>" + u); //正常 null 错误 返回报错信息
            }).exceptionally((e) -> {
                System.out.println(e.getMessage()); //打印错误信息
                return "fault";
            }).get()); //get() 正确 返回正确的返回值 错误 返回的返回值
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
